package com.example.webproject.service.impl;

import com.example.webproject.entity.User;
import com.example.webproject.exception.NotFoundException;
import com.example.webproject.repository.UserRepository;
import com.example.webproject.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author hhs
 * @Description
 * @date 2022/12/9 23:05
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository userRepository;

    /**
     * 通过id查询用户信息
     * @param id
     * @return
     */
    @Override
    public User getUser(Long id) {
        return userRepository.findById(id).get();
    }

    /**
     * 查询用户列表
     * @return
     */
    @Override
    public List<User> listUser() {
        return userRepository.findAll();
    }

    /**
     *新增用户
     * @param user
     */
    @Override
    public void saveUser(User user) {
        User newUser = new User();
       BeanUtils.copyProperties(user,newUser);
       userRepository.save(newUser);
    }

    /**
     * 通过id更新用户
     * @param id
     * @param user
     * @return
     */
    @Override
    public User updateUser(Long id,User user) {
//        Long userId=user.getId();
        User oldUser = userRepository.findById(id).get();
        if (oldUser==null){
            throw new NotFoundException("该用户不存在");
        }
//        设置id不然会 报：异常消息：com.example.webproject.entity实例的标识符。用户从1更改为空
        user.setId(id);
        user.setUpdateTime(new Date());
        BeanUtils.copyProperties(user,oldUser);
        return userRepository.save(oldUser);
    }

    /**
     * 通过id删除用户
     * @param id
     */
    @Override
    public void deleteUser(Long id) {
        userRepository.deleteById(id);
    }
}
